// 该功能已经写好配置测试文件，在终端输入 npm run ws-server即可 
// 如果需要修改端口号，请修改配置文件

import { WebSocketServer, WebSocket } from 'ws';
import net from 'net';
import { Position, TrainData } from '@/types/train';

class WSServer {
    // 端口号
    private port: number;
    // websocket服务器
    private wss: WebSocketServer | null;
    // 客户端集合
    private clients: Set<WebSocket>;
    // 当前速度
    private currentSpeed: number;
    // 当前位置
    private currentPosition: Position;
    // 固定车次号
    private fixedLine: string;

    // 构造函数
    constructor(port: number = 30000) {
        this.port = port;
        this.wss = null;
        this.clients = new Set();
        // 初始化固定值
        this.currentSpeed = 0;
        this.currentPosition = { km: 0, m: 0 };
        this.fixedLine = Math.floor(Math.random() * 90000 + 10000).toString();
    }
    // 检查端口是否被占用
    private async checkPort(): Promise<boolean> {
        return new Promise((resolve) => {
            const server = net.createServer();
            server.once('error', (err: NodeJS.ErrnoException) => {
                if (err.code === 'EADDRINUSE') {
                    console.error(`端口 ${this.port} 已被占用，请尝试其他端口`);
                    resolve(false);
                } else {
                    console.error('端口检查错误:', err);
                    resolve(false);
                }
            });
            server.once('listening', () => {
                server.close();
                resolve(true);
            });
            server.listen(this.port);
        });
    }
    // 启动服务器
    public async start(): Promise<void> {
        try {
            const isPortAvailable = await this.checkPort();
            if (!isPortAvailable) {
                return;
            }

            this.wss = new WebSocketServer({ port: this.port });
            console.log(`WebSocket服务器已启动，监听端口: ${this.port}`);
            console.log(`WebSocket地址: ws://127.0.0.1:${this.port}`);

            this.wss.on('connection', (ws: WebSocket) => {
                console.log('新客户端已连接');
                this.clients.add(ws);

                // Send initial data
                this.sendData(ws);

                // Set up heartbeat interval
                const interval = setInterval(() => {
                    this.sendData(ws);
                }, 20);

                ws.on('close', () => {
                    console.log('客户端已断开连接');
                    this.clients.delete(ws);
                    clearInterval(interval);
                });

                ws.on('error', (error: Error) => {
                    console.error('WebSocket错误:', error);
                });
            });

            this.wss.on('error', (error: Error) => {
                console.error('WebSocket服务器错误:', error);
            });

        } catch (error) {
            console.error('启动服务器时发生错误:', error);
        }
    }
    // 生成随机数据
    private generateRandomData(): TrainData {
        // 1. 速度变化在10以内
        const speedChange = Math.floor(Math.random() * 21) - 10; // -10 到 +10
        this.currentSpeed = Math.max(0, this.currentSpeed + speedChange);
        const speed = this.currentSpeed.toString();

        // 2. 位置只能增加，满1000米进位
        const metersToAdd = Math.floor(Math.random() * 100); // 每次增加0-99米
        this.currentPosition.m += metersToAdd;
        
        // 处理进位
        if (this.currentPosition.m >= 1000) {
            this.currentPosition.km += Math.floor(this.currentPosition.m / 1000);
            this.currentPosition.m = this.currentPosition.m % 1000;
        }
        
        const position = `K${this.currentPosition.km}+${this.currentPosition.m.toString().padStart(3, '0')}`;
        
        // 3. 使用固定的车次号
        const line = this.fixedLine;
        
        const now = new Date();
        const time = now.toTimeString().slice(0, 8);
        const date = now.toISOString().slice(2, 10).replace(/-/g, '-');
        const signal = Math.floor(Math.random() * 10 + 1).toString();

        return {
            speed,
            position,
            line,
            time,
            date,
            signal
        };
    }
    // 发送数据
    private sendData(ws: WebSocket): void {
        if (ws.readyState === WebSocket.OPEN) {
            const data = this.generateRandomData();
            ws.send(JSON.stringify(data));
        }
    }
    // 停止服务器
    public stop(): void {
        if (this.wss) {
            this.wss.close(() => {
                console.log('WebSocket服务器已停止');
            });
        }
    }
}

// 直接启动服务器
const server = new WSServer();
server.start();

// 处理优雅关闭
process.on('SIGINT', () => {
    server.stop();
    process.exit();
});

// export default WSServer; 